//
//  RootViewController.m
//  RunSketch
//
//  Created by Brian Hinch on 7/8/08.
//  Copyright Tellart 2008. All rights reserved.
//

#import "RootViewController.h"
#import "MainViewController.h"
#import "FlipsideViewController.h"

@implementation RootViewController

@synthesize infoButton;
@synthesize flipsideNavigationBar;
@synthesize mainViewController;
@synthesize flipsideViewController;


- (void)viewDidLoad {
	
	MainViewController *viewController = [[MainViewController alloc] initWithNibName:@"MainView" bundle:nil];
	self.mainViewController = viewController;
	[viewController release];
	
	[self.view insertSubview:mainViewController.view belowSubview:infoButton];
    
	//load app defaults
	[self loadUserPreferences];

	[[NSUserDefaults standardUserDefaults] setObject:@"Did not shut down" forKey:kUserDefaultsKey_LastShutdownStatus];
	
    [self.mainViewController loadSketch];
}

- (void)loadUserPreferences {
	NSLog(@"Loading user preferences...");
	//use the standard defaults
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	
	NSString *defaultSketchServerName = [defaults stringForKey:kUserDefaultsKey_SketchServerName];
	if (defaultSketchServerName != nil) {
		NSLog(@"loadUserPreferences: defaultSketchServerName = %@", defaultSketchServerName);
		[self.mainViewController setSketchServerName:defaultSketchServerName];
	}

	NSInteger serverFlowControlEnabled = [defaults integerForKey:kUserDefaultsKey_ServerFlowControlEnabled];
	NSLog(@"loadUserPreferences: serverFlowControlEnabled = %i", serverFlowControlEnabled);
	[self.mainViewController setFlowControlState:serverFlowControlEnabled];

	NSInteger iopackBoostEnabled = [defaults integerForKey:kUserDefaultsKey_IOPackBoostEnabled];
	NSLog(@"loadUserPreferences: iopackBoostEnabled = %i", iopackBoostEnabled);
	[self.mainViewController setIOPackBoostState:iopackBoostEnabled];

	NSString *lastShutdownStatus = [defaults stringForKey:kUserDefaultsKey_LastShutdownStatus];
	if (lastShutdownStatus != nil) {
		NSLog(@"loadUserPreferences: lastShutdownStatus = %@", lastShutdownStatus);
	} else {
		NSLog(@"loadUserPreferences: lastShutdownStatus = nil");
	}
	
	//clean up
	//[defaultSketchServerName release];
}
- (void)storeUserPreferences {
	NSLog(@"Storing user preferences...");
	//use the standard defaults
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

	NSString *defaultSketchServerName = [flipsideViewController getSketchServerNameInUI];
	NSLog(@"storeUserPreferences: defaultSketchServerName = %@", defaultSketchServerName);
	[defaults setObject:defaultSketchServerName forKey:kUserDefaultsKey_SketchServerName];
	
	int serverFlowControlEnabled = [self.mainViewController getFlowControlState];
	NSLog(@"storeUserPreferences: serverFlowControlEnabled = %i", serverFlowControlEnabled);
	[defaults setInteger:serverFlowControlEnabled forKey:kUserDefaultsKey_ServerFlowControlEnabled];

	int iopackBoostEnabled = [self.mainViewController getIOPackBoostState];
	NSLog(@"storeUserPreferences: iopackBoostEnabled = %i", iopackBoostEnabled);
	[defaults setInteger:iopackBoostEnabled forKey:kUserDefaultsKey_IOPackBoostEnabled];

	//clean up
	//[defaultSketchServerName release];
}


- (void)loadFlipsideViewController {
	
	FlipsideViewController *viewController = [[FlipsideViewController alloc] initWithNibName:@"FlipsideView" bundle:nil];
	self.flipsideViewController = viewController;
	[viewController release];
	
	// Set up the navigation bar
	UINavigationBar *aNavigationBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 44.0)];
	aNavigationBar.barStyle = UIBarStyleBlackOpaque;
	self.flipsideNavigationBar = aNavigationBar;
	[aNavigationBar release];
	
	UIBarButtonItem *buttonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(toggleView)];
	UINavigationItem *navigationItem = [[UINavigationItem alloc] initWithTitle:@"RunSketch"];
	navigationItem.rightBarButtonItem = buttonItem;
	[flipsideNavigationBar pushNavigationItem:navigationItem animated:NO];
	[navigationItem release];
	[buttonItem release];
}


- (IBAction)toggleView {	
	/*
	 This method is called when the info or Done button is pressed.
	 It flips the displayed view from the main view to the flipside view and vice-versa.
	 */
	NSLog(@"toggleView started");
	if (flipsideViewController == nil) {
		[self loadFlipsideViewController];
	}
	
	
	UIView *mainView = mainViewController.view;
	UIView *flipsideView = flipsideViewController.view;
	
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationDuration:1];
	[UIView setAnimationTransition:([mainView superview] ? UIViewAnimationTransitionFlipFromRight : UIViewAnimationTransitionFlipFromLeft) forView:self.view cache:YES];
	
	if ([mainView superview] != nil) {
		[flipsideViewController viewWillAppear:YES];
		[mainViewController viewWillDisappear:YES];
		[mainView removeFromSuperview];
        [infoButton removeFromSuperview];
		[self.view addSubview:flipsideView];
		[self.view insertSubview:flipsideNavigationBar aboveSubview:flipsideView];
		[mainViewController viewDidDisappear:YES];
		[flipsideViewController viewDidAppear:YES];

		//make any necessary changes to the flipside UI before it comes into view
		[flipsideViewController setSketchServerNameInUI:[mainViewController getSketchServerName]];
		[flipsideViewController setFlowControlStateInUI:[mainViewController getFlowControlState]];
		[flipsideViewController setIOPackBoostStateInUI:[mainViewController getIOPackBoostState]];

	} else {
		[mainViewController viewWillAppear:YES];
		[flipsideViewController viewWillDisappear:YES];
		[flipsideView removeFromSuperview];
		[flipsideNavigationBar removeFromSuperview];
		[self.view addSubview:mainView];
		[self.view insertSubview:infoButton aboveSubview:mainViewController.view];
		[flipsideViewController viewDidDisappear:YES];
		[mainViewController viewDidAppear:YES];

		//make setting changes based on changes in the flipside view UI
		[mainViewController setFlowControlState:[flipsideViewController getFlowControlStateInUI]];
		[mainViewController setIOPackBoostState:[flipsideViewController getIOPackBoostStateInUI]];
		//always set the server name last because it reloads the sketch
		[mainViewController setSketchServerName:[flipsideViewController getSketchServerNameInUI]];
		
		//store setting changes
		[self storeUserPreferences];
		
	}
	[UIView commitAnimations];

	NSLog(@"toggleView finished");
}

/*******************************************************************
 *
 * updates the sketch files the server address specified in sketchServerTextField
 */
- (IBAction)updateSketchFromServer {
    //display an alert to tell the user what to expect on the server
    UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"Open Sketch" message:@"Please select the sketch to open with the file chooser dialog box on the sketch server." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alertView show];
    [alertView release];

	//tell the view
    [flipsideViewController didStartSketchUpdate];
    
    //NSLog([NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://192.168.10.101:8080/"]]);
    NSString *urlString = [NSString stringWithFormat:kSketchUpdateURLFormatString, [flipsideViewController getSketchServerNameInUI]];
    
    //sketchUpdater will be released in didFinishUpdating
    sketchUpdater = [SketchUpdateController alloc];
    [sketchUpdater retain];
    [sketchUpdater setWatcher:self];

    NSLog([NSString stringWithFormat:@"Updating sketch from %@", urlString]);
    [sketchUpdater updateFromURL:[NSURL URLWithString:urlString]];
    
    //cleanup
    //[urlString release];
}
/*
 * cancels a running sketch update
 */
- (IBAction)cancelSketchUpdate {
    [sketchUpdater stop];
}


/*******************************************************************
 * from SketchUpdateWatcher
 */
-(void) didFailWithConnectionError: (SketchUpdateController *)c {
    [flipsideViewController didFailWithConnectionError: c];
    //release the SketchUpdateController
    NSLog(@"RootViewController: releaseing sketchUpdater");
    [c release];
}
-(void) didFailWithCommunicationError: (SketchUpdateController *)c:(NSString *)msg {
    [flipsideViewController didFailWithCommunicationError: c: msg];
    //release the SketchUpdateController
    NSLog(@"RootViewController: releaseing sketchUpdater");
    [c release];
}
-(void) didFailWithCatalogParserError: (SketchUpdateController *)c: (NSError *)err {
    [flipsideViewController didFailWithCatalogParserError: c: err];
    //release the SketchUpdateController
    NSLog(@"RootViewController: releaseing sketchUpdater");
    [c release];
}
-(void) didLoadCatalog: (SketchUpdateController *)c {
    [flipsideViewController didLoadCatalog: c];
}
-(void) madeProgress: (SketchUpdateController *)c: (int)bytesLoaded: (int)bytesTotal {
    [flipsideViewController madeProgress: c: bytesLoaded: bytesTotal];
}
-(void) didSucceed: (SketchUpdateController *)c {
    [flipsideViewController didSucceed: c];
    //release the SketchUpdateController
    NSLog(@"RootViewController: releaseing sketchUpdater");
    [c release];
	//flip it over
    [self toggleView];
    //reload the sketch
    [mainViewController loadSketch];
}
-(void) didStop: (SketchUpdateController *)c {
    [flipsideViewController didStop: c];
    //release the SketchUpdateController
    NSLog(@"RootViewController: releaseing sketchUpdater");
    [c release];
}
/*******************************************************************/


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
	// Return YES for supported orientations
	return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


- (void)didReceiveMemoryWarning {
	[super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
	// Release anything that's not essential, such as cached data
}


- (void)dealloc {
	NSLog(@"RootViewController dealloc");

	[infoButton release];
	[flipsideNavigationBar release];
	[mainViewController release];
	[flipsideViewController release];
    if (sketchUpdater) {
        [sketchUpdater stop];
        [sketchUpdater release];
    }
	[super dealloc];
}


@end
